library(ggplot2)
library(intgrr)

grr.getAllData <- function(x,k,n,r,sig,tole) {
    xbarValue <<- GRRXbar(x,k,n,r)
    rangeValue <<- GRRRange(x,k,n,r)
    appValue <<- as.vector(t(GRRAppraiser(x,k,n,r)))
    partValue <<- as.vector(t(GRRPart(x,k,n,r)))

    aplotValue <<- GRRPAPlot(x,k,n,r)
    componentValue <<- GRRComponent(x,k,n,r,sig,tole)
}

grr.buildXbar <- function(x,k,n,r,sig,tole) {
    tryCatch({
        # k=operator, n=part, r=trial
        xbarV <- GRRXbar(x,k,n,r)
        vlength <- length(xbarV)

        lsLine <- xbarV[(vlength - 2): vlength]
        cy <- xbarV[1: (vlength - 3)]
        cx <- c(1:length(cy))

        xMax <- max(cx)
        xlength <- length(cy)

        linex <- seq(0, xMax, length=xlength)
        ucl <- rep(lsLine[1], times=xlength)
        ct <- rep(lsLine[2], times=xlength)
        lcl <- rep(lsLine[3], times=xlength)

        dc <- data.frame(x=cx, y=cy)

        xmean <- mean(range(cx))
        dv<-NULL
        dvt<-NULL
        p <- ggplot(dc)
        p <- p + geom_line(aes(x=x,y=y), colour="#3276B1")
        p <- p + geom_point(aes(x=x,y=y), colour="#3276B1")
        p <- p + geom_line(aes(x=linex,y=ucl), colour="brown")+ annotate("text",x=xmean,y=ucl,label=paste("UCL=", sprintf("%.4f", ucl)),size=3.5,hjust=.5,vjust=-.4, colour="brown", alpha=1)
        p <- p + geom_line(aes(x=linex,y=ct), colour="#C79121")+ annotate("text",x=xmean,y=ct,label=paste("C=", sprintf("%.4f", ct)),size=3.5,hjust=.5,vjust=-.4, colour="#C79121", alpha=1)
        p <- p + geom_line(aes(x=linex,y=lcl), colour="brown")+ annotate("text",x=xmean,y=lcl,label=paste("LCL=", sprintf("%.4f", lcl)),size=3.5,hjust=.5,vjust=-.4, colour="brown", alpha=1)
        for (i in 1 : k) {
            dv[i] <- (n*i - 1)
            dvt[i] <- paste("Operator", i)
            if(i != k){
                p <- p + geom_vline(xintercept=(n*i + 0.5), linetype="dashed",colour="#71843F")
            }
        }
        p <- p + scale_x_continuous(breaks=dv,labels=dvt)
        p <- p + xlab("")
        p <- p + ylab("")
        p <- p + ggtitle("X-Bar Chart")
    }, error = function(e) {
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })
    return(p)
}

grr.buildR <- function(x,k,n,r) {
    tryCatch({
        # k=operator, n=part, r=trial
        xbarV <- GRRRange(x,k,n,r)
        vlength <- length(xbarV)

        lsLine <- xbarV[(vlength - 2): vlength]
        cy <- xbarV[1: (vlength - 3)]
        cx <- c(1:length(cy))

        xMax <- max(cx)
        xlength <- length(cy)

        linex <- seq(0, xMax, length=xlength)
        ucl <- rep(lsLine[1], times=xlength)
        ct <- rep(lsLine[2], times=xlength)
        lcl <- rep(lsLine[3], times=xlength)

        dc <- data.frame(x=cx, y=cy)

        xmean <- mean(range(cx))
        dv<-NULL
        dvt<-NULL
        p <- ggplot(dc)
        p <- p + geom_line(aes(x=x,y=y), colour="#3276B1")
        p <- p + geom_point(aes(x=x,y=y), colour="#3276B1")
        p <- p + geom_line(aes(x=linex,y=ucl), colour="brown")+ annotate("text",x=xmean,y=ucl,label=paste("UCL=", sprintf("%.4f", ucl)),size=3.5,hjust=.5,vjust=-.4, colour="brown", alpha=1)
        p <- p + geom_line(aes(x=linex,y=ct), colour="#C79121")+ annotate("text",x=xmean,y=ct,label=paste("C=", sprintf("%.4f", ct)),size=3.5,hjust=.5,vjust=-.4, colour="#C79121", alpha=1)
        p <- p + geom_line(aes(x=linex,y=lcl), colour="brown")+ annotate("text",x=xmean,y=lcl,label=paste("LCL=", sprintf("%.4f", lcl)),size=3.5,hjust=.5,vjust=-.4, colour="brown", alpha=1)
        for (i in 1 : k) {
            dv[i] <- (n*i - 1)
            dvt[i] <- paste("Operator", i)
            if(i != k){
                p <- p + geom_vline(xintercept=(n*i + 0.5), linetype="dashed",colour="#71843F")
            }
        }
        p <- p + scale_x_continuous(breaks=dv,labels=dvt)
        p <- p + xlab("")
        p <- p + ylab("")
        p <- p + ggtitle("R Chart")
    }, error = function(e) {
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })
    return(p)
}

grr.buildResByAppraiser <- function(x,k,n,r) {
    tryCatch({
        # k=operator, n=part, r=trial
        appV <- GRRAppraiser(x,k,n,r)

        colLength <- n*r

        avgV <- appV[, colLength + 1]
        testV <- appV[, 1: (colLength)]

        opy<- t(t(as.vector(t(testV))))[, 1]
        opx<- gl(k, colLength)
        ax <- c(1 : (k*n*r))
        ay <- NULL
        dvt <- NULL
        dv<-c(1:k)
        for (i in 1 : k) {
            dvt[i]<-paste("Operator", i)
            ay <- c(ay, rep(avgV[i], times=(colLength)))
        }
        dc <- data.frame(x=opx, y=opy, ax=ax, ay=ay)

        p <- ggplot(dc)
        p <- p + geom_point(aes(x=x,y=y), colour="#3276B1")
        p <- p + geom_point(aes(x=x,y=ay), colour="brown")
        p <- p + geom_line(aes(x=x,y=ay,group=1), colour="brown")
        p <- p + scale_x_discrete(breaks=dv,labels=dvt)
        p <- p + xlab("")
        p <- p + ylab("")
        p <- p + ggtitle("R&R Plot - By Appraisers")
    }, error = function(e) {
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })
    return(p)
}

grr.buildResByPart <- function(x,k,n,r) {
    tryCatch({
        # k=operator, n=part, r=trial
        appV <- GRRPart(x,k,n,r)

        colLength <- k*r
        avgV <- appV[, colLength + 1]
        testV <- appV[, 1: (colLength)]

        opy<- as.vector(t(testV))
        opx<- gl(n, colLength)
        #    ax <- c(1 : (k*n*r))
        ay <- NULL
        dvt <- NULL
        dv<-c(1:n)
        for (i in 1 : n) {
            dvt[i]<-paste("Part", i)
            ay <- c(ay, rep(avgV[i], times=(colLength)))
        }
        dc <- data.frame(x=opx, y=opy, ay=ay)

        p <- ggplot(dc)
        p <- p + geom_point(aes(x=x,y=y), colour="#3276B1")
        p <- p + geom_point(aes(x=x,y=ay), colour="brown")
        p <- p + geom_line(aes(x=x,y=ay,group=1), colour="brown")
        p <- p + scale_x_discrete(breaks=dv,labels=dvt)
        p <- p + xlab("")
        p <- p + ylab("")
        p <- p + ggtitle("R&R Plot - By Parts")
    }, error = function(e) {
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })
    return(p)
}

grr.buildComponents <- function(x,k,n,r) {
    tryCatch({
        # k=operator, n=part, r=trial
        componentValue <- GRRComponent(x,k,n,r,sig,tole)
        xlength <- length(componentValue[,1])
        rowname<-NULL
        xValue<-NULL
        bar <- c("Contribution","Variation","Tolerance")
        for (i in 1 : xlength) {
            rowname <- c(rowname,componentValue[i,])
            xValue<-c(xValue, c(1:4))
        }
        trow <- t(t(rowname))

        dc<- data.frame(value=as.vector(trow), x=xValue, barname=gl(3,4))
        p<-ggplot(dc)
        p<-p+geom_bar(aes(x=x,y=value,fill=barname), position="dodge", stat="identity")
        p<-p+geom_text(aes(x=x,y=value,label = paste(value, "%"),fill=barname),position=position_dodge(.9),vjust=-0.5, size=3)
#        p<-p+ylim(c(0,max(dc$value)))
        p<-p+scale_fill_discrete(labels = bar)
#        p<-p+scale_fill_manual(values = c("#99CCCC", "#FFCC99","#FFCCCC"))
        p <- p + scale_x_continuous(breaks=c(1:4), labels=c("Repeatability","Reproducibility","Gage R&R","Parts"))
        p <- p + ggtitle("Components of Variation")
    }, error = function(e) {
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })
    return(p)
}

grr.buildPlot <- function(x,k,n,r) {
    tryCatch({
        # k=operator, n=part, r=trial
        grrPlot <- GRRPAPlot(x,k,n,r)
        xlength <- length(grrPlot[,1])
        value <- NULL
        for (i in 1 : xlength) {
            value <- c(value,grrPlot[i,])
        }
        oLabel <- NULL
        oValue <- NULL
        oData <- NULL
        count <- 0
        xLabel <- NULL
        xValue <- NULL
        for(i in 1: k) {
            m <- 0
            for (j in 1: n) {
                count <- count+1
                m <- m+1
                xLabel[count] <- paste("Part", m)
                xValue[count] <- m
                oValue[count] <- i
            }
            oLabel[i] <- paste("Operator", i)
            oData[i] <- i
        }
        dc<- data.frame(avg=value, part=xValue, operator=factor(oValue))
        p<-ggplot(dc)
        p<-p+geom_line(aes(x=part,y=avg,colour=operator))
        p<-p+geom_point(aes(x=part,y=avg,colour=operator))
        p<-p+expand_limits(x=c(0, n+1))
        p <- p + scale_colour_discrete(labels=oLabel)
        p <- p + scale_x_continuous(breaks=xValue,labels=xLabel)
        p <- p + ggtitle("Part by Appraisers Plot")
    }, error = function(e) {
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })
    return(p)
}

grr.buildCharts <- function(xdatas) {
    if(!is.null(xdatas$xbar)) {
        png(xdatas$xbar, width=800, height=500)
        print(grr.buildXbar(x,k,n,r))
        dev.off()
    }

    if(!is.null(xdatas$r)) {
        png(xdatas$r, width=800, height=500)
        print(grr.buildR(x,k,n,r))
        dev.off()
    }
    if(!is.null(xdatas$rba)) {
        png(xdatas$rba, width=800, height=500)
        print(grr.buildResByAppraiser(x,k,n,r))
        dev.off()
    }
    if(!is.null(xdatas$rbp)) {
        png(xdatas$rbp, width=800, height=500)
        print(grr.buildResByPart(x,k,n,r))
        dev.off()
    }

    if(!is.null(xdatas$comp)) {
        png(xdatas$comp, width=800, height=500)
        print(grr.buildComponents(x,k,n,r))
        dev.off()
    }

    if(!is.null(xdatas$plot)) {
        png(xdatas$plot, width=800, height=500)
        print(grr.buildPlot(x,k,n,r))
        dev.off()
    }
}

eval(parse(text=funName))
